package com.example.myandroidtest.ui.notification;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import com.example.myandroidtest.R;
import com.example.myandroidtest.databinding.ActivityNotificationBinding;

public class NotificationActivity extends AppCompatActivity {

    ActivityNotificationBinding binding;
    NotificationManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityNotificationBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
    }

    private void initView() {
        binding.toolbar.ivBack.setOnClickListener(v -> finish());
        binding.toolbar.tvTitle.setText("通知栏");

        binding.btnCheck.setOnClickListener(v -> {
            checkNotification();
        });

        binding.btnShow.setOnClickListener(v -> {
            createNotification();
        });

        binding.btnHide.setOnClickListener(v -> {
            manager.deleteNotificationChannel(CHANNEL_ID);
        });

    }

    void checkNotification() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            // 申请通知权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.POST_NOTIFICATIONS}, 1);
        } else {
            // 直接使用通知
            createNotification();
        }
    }

    String CHANNEL_ID = "channel_id";

    private void createNotification() {
        //创建一个通知栏
        Notification notification =
                new NotificationCompat.Builder(this, CHANNEL_ID).setSmallIcon(R.drawable.ic_music_note).setContentTitle("标题").setContentText("文本内容").setAutoCancel(true).build();

        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "音乐播放服务",
                NotificationManager.IMPORTANCE_DEFAULT);
        manager.createNotificationChannel(channel);
        manager.notify(1, notification);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults, int deviceId) {
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            checkNotification();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults, deviceId);
    }
}